import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Button, message, Image, Popconfirm } from 'antd';
import { FormattedMessage, useRequest } from '@umijs/max';
import { FooterToolbar, PageContainer, ProForm, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { removeProduct, product } from '@/services/ant-design-pro/product';
import ProductCategoryMenu from './components/Menu';
import FormDrawer from './components/FormDrawer'; // 引入封装好的 FormDrawer 组件

const ProductList: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const [imageUrl, setImageUrl] = useState<string | undefined>(undefined);
    const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<API.ProductListItem | undefined>(undefined);
    const [selectedRowsState, setSelectedRows] = useState<API.ProductListItem[]>([]);
    const [key, setKey] = useState('1');
    const [activeKey, setActiveKey] = useState<string>('1');
    const [toolbarItems, setToolbarItems] = useState<any[]>([]);
    const [messageApi, contextHolder] = message.useMessage();
    const [form] = ProForm.useForm();

    const { run: delRun, loading } = useRequest(removeProduct, {
        manual: true,
        onSuccess: () => {
            setSelectedRows([]);
            actionRef.current?.reloadAndRest?.();
            messageApi.success('删除成功');
        },
        onError: () => {
            messageApi.error('删除失败，请重试');
        },
    });
    useEffect(() => {
        // 根据 key 的值动态更新 toolbar 的 items
        let items = [
            {
                key: '1',
                label: <span>产品特点</span>,
            },
            {
                key: '2',
                label: <span>产品优势</span>,
            },
            {
                key: '3',
                label: <span>产品案例</span>,
            },
            {
                key: '4',
                label: <span>服务能力</span>,
            },
            {
                key: '5',
                label: <span>应用场景</span>,
            },
        ];

        // 可以在此添加更多基于 key 的逻辑
        if (key === '1') {
            items[1].label = <span>API</span>;
        }

        setToolbarItems(items);
    }, [key]); // 每当 key 
    const columns: ProColumns<API.ProductListItem>[] = [
        {
            title: '标题',
            width: 150,
            ellipsis:true,
            dataIndex: 'attributeTitle',
            render: (text, record) => (
                <a onClick={() => handleDrawerOpen(record)}>{text}</a>
            ),
        },
        {
            title: '描述',
            dataIndex: 'attributeSubtitle',
            search: false,
            ellipsis: true,
            width: 200,
            hidden: ((key === '1'&& activeKey === '2') || activeKey === '5') ? true : false
        },
        {
            width: (activeKey === '3' || activeKey === '5') ? 160 : 60,
            title: '图片',
            dataIndex: 'attributeUrl',
            render: (text) => <Image src={text} alt="图片" style={{ objectFit: 'contain', width: (activeKey === '3' || activeKey === '5') ? 150 : 40, height: 40 }} />,
            search: false,
            hidden: (key === '1'&& activeKey === '2') ? true : false
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'date',
            search: false,
            ellipsis: true,
            hidden: true
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            valueType: 'date',
            search: false,
            ellipsis: true,
        },
        {
            title: '排序',
            width: 60,
            dataIndex: 'sort',
            valueType: 'digit',
            search: false,
            align: 'center',
        },
        {
            title: '操作',
            width: 80,
            dataIndex: 'option',
            valueType: 'option',
            fixed: 'right',
            render: (_, record) => [
                <a
                    key="edit"
                    onClick={() => handleDrawerOpen(record)}
                >
                    编辑
                </a>,
                <Popconfirm
                    key="delete"
                    title="确定删除该项吗？"
                    onConfirm={(event?: React.MouseEvent<HTMLElement>) => {
                        event?.stopPropagation();
                        handleRemove([record])
                    }}
                    onCancel={(event?: React.MouseEvent<HTMLElement>) => {
                        event?.stopPropagation(); // 阻止事件冒泡
                    }} 
                >
                    <a
                        key="delete"
                    >
                        删除
                    </a>
                </Popconfirm>
            ],
        },
    ];

    const handleDrawerOpen = (record?: API.ProductListItem) => {

        setCurrentRow(record);
        if (record) {
            form.setFieldsValue(record);
        } else {
            form.resetFields()
        }
        setImageUrl(record?.attributeUrl || '');
        setDrawerVisible(true);
    };

    const handleDrawerClose = () => {
        setCurrentRow(undefined);
        setDrawerVisible(false);
    };

    const handleRemove = useCallback(
        async (selectedRows: API.ProductListItem[]) => {
            if (!selectedRows?.length) {
                messageApi.warning('请选择要删除的项');
                return;
            }
            await delRun({
                params: {
                    id: selectedRows.map((row) => row.id).join(','),
                },
            });
        },
        [delRun],
    );

    const handleFinish = () => {
        actionRef.current?.reload();
    };

    const handleCategorySelect = (key: string) => {
        setKey(key);
        actionRef.current?.reload();
    };

    const renderBadge = (count: number, isActive: boolean) => {
        return isActive ? <span>({count})</span> : <span>{count}</span>;
    };

    return (
        <PageContainer header={{ title: '' }}>
            {contextHolder}

            <ProTable<API.ProductListItem, API.PageParams>
                headerTitle="产品列表"
                actionRef={actionRef}
                rowKey="id"
                search={false}
                toolbar={{
                    menu: {
                        type: 'tab',
                        activeKey: activeKey,
                        items: toolbarItems,
                        onChange: (key) => {
                            setActiveKey(key as string);
                            actionRef.current?.reloadAndRest();
                        },
                    },
                    actions: [
                        <Button
                            key="create"
                            type="primary"
                            onClick={() => handleDrawerOpen()}
                        >
                            新建
                        </Button>,
                    ]
                }}

                request={(params) => product({ ...params, productId: key, type: activeKey })}
                columns={columns}
                // rowSelection={{
                //     onChange: (_, selectedRows) => {
                //         setSelectedRows(selectedRows);
                //     },
                // }}
                tableRender={(_, dom) => (
                    <div
                        style={{
                            display: 'flex',
                            width: '100%',
                        }}
                    >
                        <ProductCategoryMenu selectedKey={key} onCategorySelect={handleCategorySelect} />
                        <div
                            style={{
                                flex: 1,
                            }}
                        >
                            {dom}
                        </div>
                    </div>
                )}

            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            <FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />{' '}
                            <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
                            <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />

                        </div>
                    }
                >
                    <Button
                        loading={loading}
                        onClick={() => {
                            handleRemove(selectedRowsState);
                        }}
                    >
                        <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
                    </Button>
                </FooterToolbar>
            )}

            <FormDrawer
                visible={drawerVisible}
                onClose={handleDrawerClose}
                currentRow={currentRow}
                onFinish={handleFinish}
                productId={key}
                type={activeKey}
                form={form}
                setImageUrl={setImageUrl}
                attributeUrl={imageUrl || ''}
            />
        </PageContainer>
    );
};

export default ProductList;